<template>
  <!-- 服务组弹窗 -->
    <Modal v-model="configVisible" :title="isEdit ? '编辑配置集' : '新增配置集'" :mask-closable="false" @on-cancel="configSetManiCancel" width="800px">
      <div class="modal-add">
        <Form ref="configSetForm" :model="configSetForm" :rules="configSetRules" :label-width="60" label-position="left">
          <FormItem label="名称" prop="id">
            <Input v-model.trim="configSetForm.id" placeholder="请输入配置集名称" :disabled="isEdit" ></Input>
          </FormItem>
          <FormItem label="文件列表">
            <Card class="file-body" v-for="file in fileList" :key="file.id">
              <Icon type="ios-close-circle" class="file-remove" @click="minusFile(file)" />
              <FormItem label="文件名:" :class="{'error-item': file.error}">
                <Input
                  v-model="file.name"
                  placeholder="如: config.js"
                  class="file-name"
                  @on-blur="nameValidate(file, 'name')">
                </Input>
                <div class="ivu-form-item-error-tip ivu-form-item-error-tip-item">{{file.message}}</div>
              </FormItem>
              <FormItem label="文件内容:">
                <Input
                  type="textarea"
                  class="txt-no-resize"
                  :rows="6" v-model="file.content"
                  placeholder="如: {port: 80}" @on-blur="$limitLen($event, 5000000)" >
                </Input>
              </FormItem>
            </Card>
            <Button type="primary" @click="addFile"><Icon type="md-add" /> 添加配置文件</Button>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="warning" @click="configSetManiCancel">取消</Button>
        <Button type="primary" :loading="isAdding" @click="configSetManiConf">确定</Button>
      </div>
    </Modal>
</template>
<script type="text/javascript">
import Fetch from '@/api/request'
import uuid from 'uuid/v4'
export default {
  data() {
    const validateName = (rule, value, callback) => {
      let regName = /^(?!-)(?!.*?-$)[a-z0-9-]{1,}$/
      if (!value) {
        callback(new Error('请输入名称'))
      } else if (!regName.test(value)) {
        callback(new Error('由小写字母、数字、-、.组成，以小写字母、数字开头和结尾'))
      } else if (value.length < 4) {
        callback(new Error('最小长度不能少于4位'))
      } else if (value.length > 32) {
        callback(new Error('最大长度不能大于32位'))
      } else {
        callback()
      }
    }

    return {
      configSetForm: {
        environmentId: '',
        id: '',
        data: {}
      },
      isAdding: false,
      configSetRules: {
        id: [{required: true, trigger: 'blur', validator: validateName}]
      },
      fileList: [],
      configVisible: false,
      isEdit: false
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    form: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  mounted() {
  },
  methods: {
    // 文件名称校验
    nameValidate(file) {
      let regName = /^(?![0-9-])[a-zA-Z0-9\-\u4e00-\u9fa5.]*$/
      if (!file.name) {
        this.$set(file, 'error', true)
        this.$set(file, 'message', '请输入名称')
      } else if (!regName.test(file.name)) {
        this.$set(file, 'error', true)
        this.$set(file, 'message', '由英文字母、数字、-、.组成，不能以数字或-开头')
      } else if (file.name.length < 4) {
        this.$set(file, 'error', true)
        this.$set(file, 'message', '最小长度不能少于4位')
      } else if (file.name.length > 128) {
        this.$set(file, 'error', true)
        this.$set(file, 'message', '最大长度不能大于128位')
      } else {
        this.$set(file, 'error', false)
      }
    },
    // 确认配置集操作
    configSetManiConf() {
      this.$refs['configSetForm'].validate((valid) => {
        if (valid) {
          // 对填入配置文件列表进行处理 1. 文件名不符合要求直接返回 2. 文件名为空直接过滤
          let temp = {}
          if (this.fileList.length > 0) {
            for (let i = 0; i < this.fileList.length; i++) {
              const f = this.fileList[i]
              if (f.error) {
                return
              } else if (f.name) {
                temp[f.name] = f.content
              }
            }
          }

          this.isAdding = true
          this.configSetForm.environmentId = this.$route.params.environmentId
          this.configSetForm.data = temp

          if (this.isEdit) {
            Fetch.put({
              url: '/api/environments/' + this.$route.params.environmentId + '/configmaps/' + this.configSetForm.id,
              params: this.configSetForm
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '配置集（' + this.configSetForm.id + '）修改成功！',
                  duration: this.DURATION
                })
                this.$emit('update:visible', false)
                this.$emit('finish', this.configSetForm.id)
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误',
                  duration: this.DURATION
                })
              }
              this.isAdding = false
            }).catch((err) => {
              this.isAdding = false
              this.$Message.error(err.message)
            })
          } else {
            Fetch.post({
              url: '/api/environments/' + this.$route.params.environmentId + '/configmaps',
              params: this.configSetForm
            }).then((res) => {
              if (res && res.code === '0') {
                this.$Message.success({
                  content: '配置集（' + this.configSetForm.id + '）添加成功！',
                  duration: this.DURATION
                })
                this.$emit('update:visible', false)
                this.$emit('finish', this.configSetForm.id)
              } else {
                this.$Message.warning({
                  content: res.message || '服务器内部错误',
                  duration: this.DURATION
                })
              }
              this.isAdding = false
            }).catch((err) => {
              this.isAdding = false
              this.$Message.error(err.message)
            })
          }
        }
      })
    },
    // 取消配置集操作
    configSetManiCancel() {
      this.$emit('update:visible', false)
    },
    // 删除文件
    minusFile(file) {
      this.fileList = this.fileList.filter((f) => {
        return f.id !== file.id
      })
    },
    // 增加文件
    addFile() {
      // 用于限制无限制添加
      if (this.fileList.length > 20) {
        this.$Message.info({
          content: '配置文件数量不能超过20个',
          duration: this.DURATION
        })
        return
      }
      this.fileList.push({
        id: uuid(),
        name: '',
        content: ''
      })
    }
  },
  watch: {
    visible(val) {
      this.configVisible = val
      if (val) {
        this.configSetForm = Object.assign({}, this.form)
        if (this.form.environmentName) {
          this.isEdit = true
          let t = []
          for (const key in this.form.data) {
            if (this.form.data.hasOwnProperty(key)) {
              const item = this.form.data[key]
              t.push({
                id: uuid(),
                name: key,
                content: item
              })
            }
          }
          this.fileList = t
        } else {
          this.isEdit = false
          this.fileList = []
        }
        this.$refs.configSetForm.resetFields()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.file-body {
  margin-bottom: 14px;
  .file-name {
    margin-bottom: 10px;
  }
  .file-remove {
    display: none;
    position: absolute;
    right: -8px;
    top: -8px;
    font-size: 22px;
    cursor: pointer;
    color: #e45049;
  }
  &:hover {
    .file-remove {
      display: block;
    }
  }
  .ivu-form-item-error-tip {
    margin-top: -13px;
  }
}
</style>
